package com.lshtv.web;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 首页，指向默认首页页面
 * 
 * @author danjingyu
 * @version $Id: IndexController.java, v 0.1 2013-5-11 下午4:55:15 danjingyu Exp $
 */
@Controller
public class CommonController {

    @RequestMapping(value = "/upload.htm")
    public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (CollectionUtils.isEmpty(fileMap)) {
            response.getWriter().print("文件为空，不能上传");
            return;
        }
        List<String> results = saveFile(request, fileMap);
        String files = "";
        for (String fileName : results) {
            files += fileName + ",";
        }
        response.getWriter().print(files.substring(0, files.length() - 1));
    }

    private List<String> saveFile(HttpServletRequest request, Map<String, MultipartFile> fileMap) {
        String path = request.getSession().getServletContext().getRealPath("upload");
        List<String> files = new ArrayList<String>();
        for (String key : fileMap.keySet()) {
            MultipartFile file = fileMap.get(key);
            //保存  
            try {
                String fileName = file.getOriginalFilename();
                int lastIndexOfDot = fileName.lastIndexOf('.');
                int fileNameLength = fileName.length();
                String extension = fileName.substring(lastIndexOfDot + 1, fileNameLength);
                String localFileName = System.currentTimeMillis() + "." + extension;
                File targetFile = new File(path, localFileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                file.transferTo(targetFile);
                files.add(localFileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return files;
    }
}
